<template>
  <div class="permission-management">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键字">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入权限名称、权限码或描述"
            clearable
            style="width: 250px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd" v-if="userStore.hasPermission('permission:create')">
            <el-icon><Plus /></el-icon>
            新增权限
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 权限表格 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="permissionList"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="权限名称" min-width="150" />
        <el-table-column prop="code" label="权限码" min-width="200">
          <template #default="{ row }">
            <el-tag type="info">{{ row.code }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
              v-if="userStore.hasPermission('permission:update')"
            >
              编辑
            </el-button>
            <el-button
              :type="row.status === 1 ? 'warning' : 'success'"
              size="small"
              @click="handleToggleStatus(row)"
              v-if="userStore.hasPermission('permission:update')"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              v-if="userStore.hasPermission('permission:delete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 权限表单对话框 -->
    <PermissionForm
      v-model:visible="formVisible"
      :permission-data="currentPermission"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import {
  getPermissionList,
  deletePermission,
  updatePermissionStatus,
  type Permission
} from '@/api/permission'
import PermissionForm from './components/PermissionForm.vue'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const permissionList = ref<Permission[]>([])
const formVisible = ref(false)
const currentPermission = ref<Permission | null>(null)

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 格式化日期
function formatDate(dateString: string) {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取权限列表
async function fetchPermissionList() {
  loading.value = true
  try {
    const response = await getPermissionList({
      page: pagination.page,
      page_size: pagination.pageSize,
      keyword: searchForm.keyword
    })

    if (response && response.list) {
      permissionList.value = response.list
      pagination.total = response.total
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
function handleSearch() {
  pagination.page = 1
  fetchPermissionList()
}

// 重置搜索
function handleReset() {
  searchForm.keyword = ''
  pagination.page = 1
  fetchPermissionList()
}

// 新增权限
function handleAdd() {
  currentPermission.value = null
  formVisible.value = true
}

// 编辑权限
function handleEdit(permission: Permission) {
  currentPermission.value = permission
  formVisible.value = true
}

// 切换权限状态
async function handleToggleStatus(permission: Permission) {
  const newStatus = permission.status === 1 ? 0 : 1
  const action = newStatus === 1 ? '启用' : '禁用'

  try {
    await ElMessageBox.confirm(
      `确定要${action}权限"${permission.name}"吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await updatePermissionStatus(permission.id, newStatus)
    ElMessage.success(`${action}权限成功`)
    fetchPermissionList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${action}权限失败:`, error)
      ElMessage.error(`${action}权限失败`)
    }
  }
}

// 删除权限
async function handleDelete(permission: Permission) {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限"${permission.name}"吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deletePermission(permission.id)
    ElMessage.success('删除权限成功')
    fetchPermissionList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除权限失败:', error)
      ElMessage.error('删除权限失败')
    }
  }
}

// 分页大小改变
function handleSizeChange(size: number) {
  pagination.pageSize = size
  pagination.page = 1
  fetchPermissionList()
}

// 当前页改变
function handleCurrentChange(page: number) {
  pagination.page = page
  fetchPermissionList()
}

// 表单提交成功
function handleFormSuccess() {
  fetchPermissionList()
}

// 初始化
onMounted(() => {
  fetchPermissionList()
})
</script>

<style scoped>
.permission-management {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-bar {
  margin-bottom: 16px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.table-container {
  flex: 1;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  overflow: auto;
  max-height: 600px;
}

.pagination {
  margin-top: 16px;
  text-align: right;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

:deep(.el-table) {
  width: 100%;
  border-radius: 0;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}
</style>
